const app = getApp();
Page({
  // 页面的初始数据
  data: {
    isGetUserInfo: false,
    userInfo: {},
  },
  //获取用户信息
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log("获取用户信息成功", res)
        let user = res.userInfo
        this.setData({
          isGetUserInfo: true,
          userInfo: user,
        })
        user.openid = app.globalData.openid;
        app.globalData.userInfo=this.data.userInfo
        app.globalData.isGetUserInfo=true
        app._saveUserInfo(user);
        //此处可改进，只调用getUserData，后台若查无，则添加，并返回
        wx.cloud.callFunction({
          name: "changeUserData",
          data: {
            action:"newUser",
            userInfo:this.data.userInfo
          }
        })
        
        this.onShow()


      },
      fail: res => {
        console.log("获取用户信息失败", res)
      }
    })
  },
  //退出登录
  logOut() {
    this.setData({
      isGetUserInfo: false,
      userInfo: {},
    })
    app.globalData.isGetUserInfo=false
    app._saveUserInfo(null);  //若没有这一行，则“退出登录”会失效
  },

  myPublishTap(){
    wx.navigateTo({
      url: '../my_publish/my_publish',
      success: (result) => {},
      fail: (res) => {},
      complete: (res) => {},
    })
  },

  myReceiveTap(){
    wx.navigateTo({
      url: '../my_receive/my_receive',
      success: (result) => {},
      fail: (res) => {},
      complete: (res) => {},
    })
  },

  myCreditTap(){
    wx.navigateTo({
      url: '../my_credit/my_credit',
    })
  },
  
  onShow() {
    var user = app.globalData.userInfo;
    if (user && user.nickName) {
      this.setData({
        isGetUserInfo: true,
        userInfo: user,
      })
      wx.cloud.callFunction({
        name:"getUserData",
        data:{
          action:"getAll",
          openid:app.globalData.openid
        },
        success:(res)=>{
          console.log("数据库中用户信息如下:\n")
          console.log(res)
          this.setData({
            "userInfo.credit":res.result.credit,
            "userInfo.taskListPublish":res.result.taskListPublish,
            "userInfo.taskListReceive":res.result.taskListReceive,
          })
          console.log(this.data.userInfo)
        },
        fail:(res)=>{
          console.log("获取数据库中用户信息失败")
          console.log(res)
        }
      })

    }
  },
})